package com.zero.guava.samples.Cache;

import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.cache.CacheLoader;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * CacheLoader<Key,value> cacheLoader = CacheLoader.from(Function<Key,Value> func);
 * 当Function对象作为CacheLoader.from方法的参数时，我们可以获取到返回的CacheLoader实例，
 * key为传入的对象，value为key经过Function转换后的值
 */
public class CacheLoaderTest {

    public static void main(String[] args) throws Exception {

        testCacheLoaderFunction();
        testCacheLoaderSupplier();
    }

    public static void testCacheLoaderFunction() throws Exception {

        Function<Date, String> function = new Function<Date, String>() {
            @Override
            public String apply(Date input) {
                return new SimpleDateFormat("yyyy-MM-dd").format(input);
            }
        };

        CacheLoader<Date, String> cacheLoader = CacheLoader.from(function);
        String load = cacheLoader.load(new Date());
        System.out.println(load);
    }

    public static void testCacheLoaderSupplier() throws Exception {

        Supplier<Long> supplier = new Supplier<Long>() {
            @Override
            public Long get() {
                return System.currentTimeMillis();
            }
        };

        /**
         * 任意传递给CacheLoader的键，都会导致Supplier的get方法被调用
         */
        CacheLoader<Object, Long> loader = CacheLoader.from(supplier);
        System.out.println(loader.load("first"));
        Thread.sleep(2000);
        System.out.println(loader.load("second"));
    }
}